package utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class PropertiesUtil {

    /**
     * 获取Properties对象
     * @return
     */
    public static Properties getProperties(String path){
        Properties properties = new Properties();
        try {
            properties.load(new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
        } catch (FileNotFoundException e) {
            System.out.println("properties文件未找到!");
        } catch (IOException e) {
            System.out.println("出现IOException");
        }
        return properties;
    }

    /**
     * 根据key查询value值
     * @param key key
     * @return
     */
    public static String getValue(String path, String key){
        Properties properties = getProperties(path);
        return properties.getProperty(key);
    }

    /**
     * 新增/修改数据
     * @param key
     * @param value
     */
    public static void setValue(String path, String key, String value){
        Properties properties = getProperties(path);
        properties.setProperty(key, value);
        try {
            OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8);
            properties.store(oStreamWriter, "");
            oStreamWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
